package com.ruoyi.common.utils;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.BusiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Slf4j
public class RequestUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static JSONObject get(String url) {
        return get(url, null);
    }

    public static JSONObject get(String url, Map<String, String> headersParam) {
        return excute(url, null, MediaType.APPLICATION_FORM_URLENCODED, HttpMethod.GET, headersParam);
    }

    public static JSONObject post(String url, MultiValueMap<String, String> param, Map<String, String> headers) {
        return excute(url, param, MediaType.APPLICATION_FORM_URLENCODED, HttpMethod.POST, headers);
    }

    public static JSONObject post1(String url, Map<String, String> param, Map<String, String> headers) {
        return excute(url, param, MediaType.APPLICATION_FORM_URLENCODED, HttpMethod.POST, headers);
    }

    /**
     * post 表单
     * <p>
     * 必须使用 MultiValueMap
     *
     * @param url
     * @param param
     * @return
     */
    public static JSONObject post(String url, MultiValueMap<String, String> param) {
        return post(url, param, null);
    }

    public static JSONObject postMap(String url, Map<String, String> map) {
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            param.add(key, map.get(key));
        }
        return post(url, param, null);
    }
    public static JSONObject postJson(String url, Object param, Map<String, String> headers) {
        return excute(url, param, MediaType.APPLICATION_JSON, HttpMethod.POST, headers);
    }

    public static JSONObject postJson(String url, Object param) {
        return postJson(url, param, null);
    }

    public static void main(String[] args) {
        testGet();
        getForHeader();
        testPost();
        testPostJson();

    }

    private static void testGet() {
        log.info("-------------------------请求方法：get-----------------------");
        JSONObject json = get("https://apiserver-dev-eda.chinagoods.com/op/public/advertisement/v1/page?pageNo=1&pageSize=10");
    }

    private static void getForHeader() {
        log.info("-------------------------请求方法：getForHeader-----------------------");
        Map<String, String> headers = new HashMap<>();
        headers.put("openId", "oyBYj472sPnfMLQytIamaNoGp5RY");
        headers.put("appid", "wx1c7a950a6ac2007d");

        JSONObject json = get("https://testwhale.chinagoods.com/ch/openapi/user/getUserInfo", headers);
    }

    private static void testPost() {
        log.info("-------------------------请求方法：post-----------------------");
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userId", "1093133");
        map.add("id", "1093133");
        map.add("nickname", "aaaaa");
        JSONObject json = post("http://127.0.0.1:8082/openapi/user/testPost", map);
    }

    private static void testPostJson() {
        log.info("-------------------------请求方法：postJson-----------------------");
        Map<String, Object> param = new HashMap<>();
        param.put("openId", "oyBYj4xbz8nf_7dMm312w0cs5nxM");
        param.put("appId", "wx1c7a950a6ac2007d");
        param.put("source", "channel");
        Map<String, String> headersParam = new HashMap<>();
        headersParam.put("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzb3VyY2VDY2NsIiwicmVzb3VyY2VPbmUiXSwic2NvcGUiOlsiVEhJUkQiLCJDQ0NMIl0sImV4cCI6MTY1NDA3OTY0NiwianRpIjoiZmNiODE4NGEtYjhmNC00OThjLWI2YTItNzAwN2YzNmM2MTM0IiwiY2xpZW50X2lkIjoiY2NjbCJ9.YVqmyLAHK_Yx7PYvpPC8YgBVoEfgpQYrfJA4mD7RpDvoZNi1YCXclsfEw2l__8g76bpDfEbCusYnbE2PzFqY35gtynV8DURZeUeFUPO2wD5BPTgVXwadyYy3XC3A2Vi2iESXwr05tr2MXjT9qLx663RDMMm1lxKS9prO5jni-Fxrabda4K5-KxUGTFiMjgTvxUiC-K7BWsOv2LAv3dcPMPle-1v7NwfCXZJKRhVWYoTBuBSP4J9QAmmUlMw9wCHumS42d-jTcq2wnXAhlSo9i31A0ON7cXL5mdSh7c2zHbVEj_8yob_Lz1km-et2p08edwNj1NQM3YPfI_6RB4trrQ");
        JSONObject json = postJson("https://testuser.chinagoods.com/user/fastTrack/registerOrLogin", param, headersParam);
    }

    private static JSONObject excute(String url, Object data, MediaType mediaType, HttpMethod method, Map<String, String> headersParam) {
        JSONObject json;
        HttpHeaders headers = new HttpHeaders();
        if (headersParam != null && !headersParam.isEmpty()) {
            Iterator<Map.Entry<String, String>> iterator = headersParam.entrySet().iterator();
            headers.setContentType(mediaType);
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                headers.add(next.getKey(), next.getValue());
            }
        }
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity(data, headers);

        try {
            ResponseEntity<String> exchange;
            exchange = restTemplate.exchange(url, method, httpEntity, String.class);
            // System.out.println(JSONObject.parseObject(exchange.getBody()));
            return JSONObject.parseObject(exchange.getBody());
        } catch (Exception e) {
            log.info("请求失败：{}", e.getMessage());
            throw new BusiException(e.getMessage());
        }
    }


    public static String request(String url, Object data, MediaType mediaType, HttpMethod method, Map<String, String> headersParam) {
        JSONObject json;
        HttpHeaders headers = new HttpHeaders();
        if (headersParam != null && !headersParam.isEmpty()) {
            Iterator<Map.Entry<String, String>> iterator = headersParam.entrySet().iterator();
            headers.setContentType(mediaType);
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                headers.add(next.getKey(), next.getValue());
            }
        }
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
       // headers.add("user-agent", "Apifox/1.0.0 (https://apifox.com)");

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity(data, headers);
//        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity(data);
        try {
            ResponseEntity<String> exchange;
            exchange = restTemplate.postForEntity(url, httpEntity, String.class);

            return exchange.getBody();
        } catch (Exception e) {
            log.info("请求失败：{}", e.getMessage());
            throw new BusiException(e.getMessage());
        }
    }
}

